package com.surpassun.emall.service.impl;

import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import com.surpassun.emall.exception.NoSuchStoreException;
import com.surpassun.emall.model.Address;
import com.surpassun.emall.model.Store;
import com.surpassun.emall.model.StoreType;
import com.surpassun.emall.model.User;
import com.surpassun.emall.repository.StoreRepository;
import com.surpassun.emall.service.StoreService;
import com.surpassun.emall.util.QueryUtil;
import com.surpassun.emall.util.Validator;

/**
 *
 * @author Denis
 */
@Service
public class StoreServiceImpl extends AbstractServiceImpl<Store> implements StoreService {

	@Inject
	StoreRepository storeRepository;
	
    public StoreServiceImpl() {
    	super(Store.class);
    }

	@Override
	public void addStore(String name, StoreType type, Address address, User owner) {
		if (validateStore(name, type, address, owner)) {
			Store store = new Store();
			store.setName(name);
			store.setType(type);
			store.setAddress(address);
			store.setOwner(owner);
			storeRepository.add(store);
		}
	}

	@Override
	public void updateStore(Store store, String name, StoreType type, Address address, User owner) {
		if (Validator.isNotNull(store) && validateStore(name, type, address, owner)) {
			store.setName(name);
			store.setType(type);
			store.setAddress(address);
			store.setOwner(owner);
			storeRepository.update(store);
		}
	}

	@Override
	public void updateStore(long storeId, String name, StoreType type, Address address, User owner) throws NoSuchStoreException {
		Store store = super.get(storeId);
		if (Validator.isNull(store)) {
			throw new NoSuchStoreException("No such store found with id : " + storeId);
		}
		
		if (validateStore(name, type, address, owner)) {
			store.setName(name);
			store.setType(type);
			store.setAddress(address);
			store.setOwner(owner);
			storeRepository.update(store);
		}
	}
    
	private boolean validateStore(String name, StoreType type, Address address, User owner) {
		return (Validator.isNotNull(name) && Validator.isNotNull(type) 
				&& Validator.isNotNull(address) && Validator.isNotNull(owner));
	}

	@Override
	public List<Store> getStoreByType(long typeId) {
		return storeRepository.getByField("type.id", typeId, QueryUtil.EQUAL);
	}

	@Override
	public List<Store> getStoreByCity(long cityId) {
		return storeRepository.getByField("address.city.id", cityId, QueryUtil.EQUAL);
	}
}